import type { ToastOptions } from 'wot-design-uni/components/wd-toast/types'
import { getCurrentPath } from '@/utils'
import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'

type ToastInput = ToastOptions | string

const TOAST_ICONS = {
  success: 'success',
  error: 'error',
  info: 'info',
  warning: 'warning',
} as const

function getDefaultOptions(): ToastOptions {
  return {
    duration: 2000,
    show: false,
  }
}
function deepMerge<T>(...objects: Partial<T>[]): T {
  const result = {} as T

  for (const obj of objects) {
    if (!obj)
      continue
    for (const key in obj) {
      const value = obj[key]
      if (value && typeof value === 'object' && !Array.isArray(value)) {
        // 如果是对象，递归合并
        result[key] = deepMerge(result[key] as any || {}, value)
      }
      else {
        // 否则直接覆盖
        result[key] = value as any
      }
    }
  }
  return result
}
function mergeToastOptions(option: ToastInput, extra?: Partial<ToastOptions>): ToastOptions {
  const base = typeof option === 'string' ? { msg: option } : option
  const merged = deepMerge(getDefaultOptions(), base, {
    position: base.position || 'middle',
    show: true,
    ...extra,
  })
  return merged as ToastOptions
}

export const useGlobalToast = defineStore('global-toast', () => {
  const toastOptions = reactive<ToastOptions>(getDefaultOptions())
  const currentPage = ref('')

  function show(option: ToastInput) {
    currentPage.value = getCurrentPath()
    const mergedOptions = mergeToastOptions(option)
    Object.assign(toastOptions, mergedOptions)
  }

  function success(option: ToastInput) {
    show(mergeToastOptions(option, { iconName: TOAST_ICONS.success, duration: 1500 }))
  }

  function error(option: ToastInput) {
    show(mergeToastOptions(option, { iconName: TOAST_ICONS.error, direction: 'vertical' }))
  }

  function info(option: ToastInput) {
    show(mergeToastOptions(option, { iconName: TOAST_ICONS.info }))
  }

  function warning(option: ToastInput) {
    show(mergeToastOptions(option, { iconName: TOAST_ICONS.warning }))
  }

  function close() {
    Object.assign(toastOptions, getDefaultOptions())
    currentPage.value = ''
  }

  return {
    toastOptions,
    currentPage,
    show,
    success,
    error,
    info,
    warning,
    close,
  }
})
